package org.example.chapter8.service.impl;

import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.example.chapter8.pojo.User;
import org.example.chapter8.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author CoderXshuai
 * @date 2020/8/4/0004 21:10
 */
@Service
public class UserServiceImpl implements UserService {
    //注入MongoDBTemplate对象
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveUser(User user) {
        //使用名称user文档保存用户信息
        mongoTemplate.save(user, "user");
        //如果文档采用类名首字符小写,则可以这样保存
        //mongoTemplate.save(user);
    }

    @Override
    public DeleteResult deleteUser(String id) {
        //构建id相等的条件
        Criteria criteria = Criteria.where("id").is(id);
        //查询对象
        Query query = Query.query(criteria);
        //删除用户
        DeleteResult result = mongoTemplate.remove(query, User.class);
        return result;
    }

    @Override
    public List<User> findUser(String userName, String note, int skip, int limit) {
        //将用户名称和备注设置为模糊查询准则
        Criteria criteria = Criteria.where("userName").regex(userName)
                .and("note").regex(note);
        //构建查询添加,并设置分页跳过前skip个,至多返回limit个
        Query query = Query.query(criteria).limit(limit).skip(skip);
        List<User> userList = mongoTemplate.find(query, User.class);
        return userList;
    }

    @Override
    public UpdateResult updateUser(String id, String userName, String note) {
        return null;
    }

    @Override
    public User getUser(String id) {
        //如果只是获取第一个,也可以采用如下查询方法
//        Criteria criteria = Criteria.where("id").is(id);
//        Query query = Query.query(criteria);
//        return mongoTemplate.findOne(query, User.class);
        return mongoTemplate.findById(id, User.class);
    }
}
